/**
 * 总路由控制文件
 *
 * @Author bian
 * @CreateDate 2018.3.1
 */

// library module
var Router = require("koa-router");

// local module
var fs = require("fs");
var path = require("path");
var util = require("util");

// my module
var db = require("./../models/index.js");
var debug = require("./../instances/debug.js");
var context = require("./../instances/context.js");
var auth  = require("../instances/auth");

var router = new Router();

/****************************
 登录过滤
 ***************************/
router.use(function *(next) {
    var ctx = this;
    context.set(ctx);
    var req = ctx.request;

    if(/\/token\/*/.test(req.url)){   //通过req.url过滤
        var user = yield auth.adminer(ctx);
        if(!user){
            ctx.redirect("/");
        }
    }
    yield next;
});

/****************************
 * 路由自动引入
 * 注意：添加新的路由文件后请重启supervisor
 ***************************/

var loadDir = (dir) => {
    fs
        .readdirSync(dir)
        .forEach( (file) => {
            var nextPath = path.join(dir, file);
            var stat = fs.statSync(nextPath);
            if (stat.isDirectory()) {
                loadDir(nextPath);
            } else if (stat.isFile() && file.indexOf(".") !== 0 && file !== "index.js") {
                require(nextPath)(router);
            }
        });
};

loadDir(__dirname);

module.exports = router.middleware();

